/*
 * Created by Federico Pisarello - SisDev Software (c) 2012 - fpisarello@sisdevsoft.com
 */

var popForm = 'recipesPop.php';
var popItemForm = 'recipesItemPop.php';
var actionForm = 'recipesAction.php';
var actionUpload = 'upload.php';

var joDataRecipe;
var oTable;

/** Variable of tracking the IndexPK **/
var actionPK = undefined;
var action = undefined;

function $_init()
{
	$('#btnRecipes').removeClass('btnMenu').addClass('btnMenuAct');
	
	var gaiSelected;
	
	$(document).ready(function() {
    	oTable = $('#dt_recipes').dataTable( {
					"bJQueryUI": true,
					"sPaginationType": "two_button",
					"bInfo": false,
					"bLengthChange": false,
					"bProcessing": true,
					"bServerSide": true,
					"sAjaxSource": actionForm + "?actionOfForm=search",
					"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
						if ( jQuery.inArray(aData[0], gaiSelected) != -1 )
						{
					        $(nRow).addClass('row_selected');
						}
						return nRow;
					},
					"aoColumns": [
					  			null,
					  			null,
					  			null,
					  			null
					  		]

				});
    	
    	/* Click event handler */
    	$('#dt_recipes tbody tr').live('click', function () {
    		var aData = oTable.fnGetData(this);
    		var iId = aData[0];
    		actionPK = aData[0];
    		
    		gaiSelected =  [];
    		if ( $(this).hasClass('row_selected') ) {
	            $(this).removeClass('row_selected');
	            actionPK = undefined;
	        }
	        else {
	            oTable.$('tr.row_selected').removeClass('row_selected');
	            $(this).addClass('row_selected');
	            gaiSelected[gaiSelected.length++] = iId;
	        }
    	} );

	});
	
	$("#recipesDialog").dialog({
		autoOpen:false, 
		height:310, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() {$("#recipesDialog").empty();},
		open: function() {
			$('#recipesDialog').css('background','url(imagenes/bg.gif)');
			//Add Click for All Buttons in Pop Form
			$('#btnSave').click( function(e) {
				$('#recipesPopForm').submit();
			});
		}
	});
	
	$("#recipesDialogItem").dialog({
		autoOpen:false, 
		height:400, 
		width:600, 
		dialogClass:'no-close',
		beforeClose: function() {$("#recipesDialogItem").empty();},
		open: function() {
			$('#recipesDialogItem').css('background','url(imagenes/bg.gif)');
			$('#btnItemAdd').click( function(e) {
				$('#recipesItemsPopForm').submit();
			});
		}
	});
	
	//Add Click for All Buttons in Search Form
	$("#btnAdd").click( function(e) {
		addProxyShow();
    });
	
	$('#btnEdit').click( function(e) {
		editProxyShow();
	});
	
	$('#btnErase').click( function(e) {
		delProxyShow();
	});
	
	$('#btnAddIngredient').click( function(e) {
		addItemProxyShow();
	});
	
	$('.btnABC').click(function (e) {
		var idBtn =  $(this).attr('id');
		if($('#'+idBtn).children().hasClass('itmAct'))
		{
			$('.abc').removeClass('itmAct');
			oTable.fnReloadAjax(actionForm + "?actionOfForm=search");
		}
		else
		{
			$('.abc').removeClass('itmAct');
			$('#' + idBtn).children().addClass('itmAct');
			oTable.fnReloadAjax(actionForm + "?actionOfForm=search&sSearchTop=" + $(this).attr('id'));
			
		}
	});
}

function createUploader(){            
    var uploader = new qq.FileUploaderBasic({
    	button: document.getElementById('fileUpload'),
        action: actionUpload,
        allowedExtensions: ['png', 'jpg', 'gif'],
        multiple: false,
        params: {
        	idRecipe : actionPK
		},
		onComplete: function(id, fileName, responseJSON){
			$("#imgRecipe").attr("src", responseJSON.completeFileName);
		}
    });    
}

function $_initPopItem()
{
	$_ValidatorSetDefaults();
	$_initItemPopValidator();
	$_initDeleteBtnItem();
	
	$('#btnItemExit').click( function(e) {
		$('#recipesDialogItem').dialog('close');
	});
	
    createUploader();
}

function $_initDeleteBtnItem()
{
	$('.btnDelItem').click(function (e) {
		var idBtn =  $(this).attr('id');

		var paramData = 'actionOfForm=delIngredient&idRecipesItem=' + idBtn;
		
	    $.ajax({
	        type: 'POST',
	        url: actionForm,
	        data: paramData,
			dataType: 'json',
	        success: function(jsonObj){
	            if(jsonObj.status === 'OK')
	            	$("#"+idBtn).closest('li').remove();
				else
					$_showMessage('ERR', jsonObj.status, jsonObj.msg);
	        }
	    });
	});	
}

function $_initPop()
{
	$("#recipesLastUpdate").mask("99/99/9999",{placeholder:" "});
	$("#recipesLastUpdate").datepicker({changeMonth: true, changeYear: true, showOn: 'button', buttonImage: 'imagenes/calendario.png', buttonImageOnly: true, dateFormat: "dd/mm/yy"});

	$('#btnExit').click( function(e) {
		$('#recipesDialog').dialog('close');
	});
	
	$_ValidatorSetDefaults();
	$_initPopValidator();
	
	var idRestaurant;
	
	//Populate User Data	
	if(action == iConst.EDIT)
	{
		$('#recipesDescription').val(joDataRecipe.description);
		$('#recipesLastUpdate').val(joDataRecipe.lastUpdate);
		idRestaurant = joDataRecipe.idRestaurant;
	}
	
	//Populate Combos
	if($('#cmbRestaurant').length > 0)
	{
		$.ajax({ 
		    url: actionForm, 
		    type:'POST', 
		    data: 'actionOfForm=getRestaurants', 
		    dataType: 'json', 
		    success: function(json) { 
		        $.each(json, function(i, value) {
		        	if(value.idRestaurant == idRestaurant)
		        		$('#cmbRestaurant').append($('<option selected>').text(value.businessName).attr('value', value.idRestaurant));
		        	else
		        		$('#cmbRestaurant').append($('<option>').text(value.businessName).attr('value', value.idRestaurant));
		        });
		    }
		});
	}
}

function addItemProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDITITEM + "&idRecipe=" + actionPK;

	$('#recipesDialogItem').load(popItemForm + '?' + paramData).dialog('open');
}

function addProxyShow()
{
	//Reset State of action and IndexPK
	actionPK = undefined;
	action = iConst.NEW;
	oTable.$('tr.row_selected').removeClass('row_selected');
	$('#recipesDialog').load(popForm).dialog('open');
}

function editProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.EDIT;
	var paramData =  "actionOfForm=" + iConst.EDIT + "&idRecipe=" + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj)
                            {
        						joDataRecipe = jsonObj;
        						//Open Pop Dialog
        						$('#recipesDialog').load(popForm).dialog('open');
                            }
        });
	
return true;
}

function $_saveIngredient()
{
	var paramData = 'actionOfForm=addIngredient&' + $("#recipesItemsPopForm").serialize() + '&idRecipe=' + actionPK;
		
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
            	$("#itmList").append('<li><button class="itmTableBtn btnDelItem" id="' + jsonObj.idItem + '">X</button>' + jsonObj.itemDescrip + '</li>');
            	$('#itemRescipesDescription').val('');
            	$('#itemRescipesQuantity').val('');
            	$_initDeleteBtnItem();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function $_saveRecipes(action)
{
	var paramData = 'actionOfForm=addOrEdit&' + $("#recipesPopForm").serialize();
	
	if(action == iConst.EDIT)
		paramData += '&idRecipe=' + actionPK;
	
    $.ajax({
        type: 'POST',
        url: actionForm,
        data: paramData,
		dataType: 'json',
        success: function(jsonObj){
            if(jsonObj.status === 'OK'){
				$_showMessage('OK', jsonObj.status, jsonObj.msg);
				$('#recipesDialog').dialog('close');
				oTable.fnReloadAjax();
			}
			else
				$_showMessage('ERR', jsonObj.status, jsonObj.msg);
        }
    });

return true;
}

function delProxyShow()
{
	if(actionPK === undefined)
	{
		$_showMessage('ALERT', 'ALERTA', strMenssageSelectionUserInGrid);
		return;
	}
	
	action = iConst.DELETE;
	
	$("#deleteRecipesDialog").dialog({
		autoOpen: false, 
		width:350,
		position: 'center',
		open: function () {
			$('#deleteRecipesDialog').css('background','url(imagenes/bg.gif)');
			$('#btnConfirmDelete').click( function(e) {
				$_del();
			});
			$('#btnExitDelete').click( function(e) {
				$('#deleteRecipesDialog').dialog('close')
			})
		}
	});
	$('#deleteRecipesDialog').dialog('open');	
}

function $_del()
{
	var paramData = 'actionOfForm=' + action + '&idRecipe=' + actionPK;

    $.ajax({
            type: 'POST',
            url: actionForm,
            data: paramData,
			dataType: 'json',
            success: function(jsonObj)
                                {
                                    if(jsonObj.status === 'OK'){
										$_showMessage('OK', 'OK', jsonObj.msg);
										
										//Reset State of action and IndexPK
										actionPK = undefined;
										action = iConst.NEW;
										oTable.fnReloadAjax();
									}
									else
										$_showMessage('ERR', 'ERROR', jsonObj.msg);
                                    $('#deleteRecipesDialog').dialog('close');
                                }
            });

return true;
}

function $_initItemPopValidator()
{
	$('#recipesItemsPopForm').validate({
		submitHandler: function() {
			$_saveIngredient(action);
		}, 		
		rules: {
			itemRescipesDescription: {required: true,minlength: 1},
			itemRescipesQuantity: {required: true,minlength: 1}
		},
		messages: {
			itemRescipesDescription: {required: '',minlength: ''},
			itemRescipesQuantity: {required: '',minlength: ''}
		}
	});
}

function $_initPopValidator()
{
	$('#recipesPopForm').validate({
		submitHandler: function() {
			$_saveRecipes(action);
		}, 		
		rules: {
			recipesDescription: {required: true,minlength: 1},
			recipesLastUpdate: {required: true,minlength: 1}
		},
		messages: {
			recipesDescription: {required: '',minlength: ''},
			recipesLastUpdate: {required: '',minlength: ''}
		}
	});
}